var PW = PW || {};

PW.pitchSearch = {

    options: function (options) {
        var _this = this;
        console.log('options:');
        console.log(options);
        //this.passedOptions = options;

        this.data = options.results.slice(0);
        this.results = options.results.slice(0);

        for (var a in _this.results) {
            var res = _this.results[a];
            $.getJSON(
                'http://maps.googleapis.com/maps/api/geocode/json',
                {
                    address: res.venue_address,
                    sensor: false
                },
                function (data) {
                    _this.data[a].location = data.results[0].geometry.location
                    _this.results[a].location = data.results[0].geometry.location;
                    console.log('res', res);
                    console.log('data', data);
                    console.log('a', a);
                    console.log('_this.data[a]', _this.data[a]);
                    console.log('location', data.results[0].geometry.location);
                }
            );
        }
    },

    load: function () {
        this.opt = {};
        this.opt.name = $('#refine-name').val();
        this.opt.date = $('#refine-date').val();
        this.opt.time = $('#refine-time').val();
        this.opt.maxPrice = $('#refine-max-price').val();
        this.opt.size = $('#refine-size').val();
        this.opt.minWidth = $('#refine-min-width').val();
        this.opt.maxWidth = $('#refine-max-width').val();
        this.opt.minLength = $('#refine-min-length').val();
        this.opt.maxLength = $('#refine-max-length').val();
        this.opt.surface = $('#refine-surface').val();
        this.opt.floodlit = $('#refine-floodlit').val();
        this.opt.goalSize = $('#refine-goal-size').val();
        this.opt.indoor = $('#refine-indoor').val();
        this.opt.nets = $('#refine-nets').val();
        this.opt.parking = $('#refine-parking').val();
        this.opt.changingRooms = $('#refine-changing-rooms').val();
        this.opt.showers = $('#refine-showers').val();
    },

    el: { },

    events: function () {
        var _this = this;

        var array = [
            ['#refine-date', 'date'],
            ['#refine-time', 'time'],
            ['#refine-max-price', 'maxPrice'],
            ['#refine-size', 'size'],
            ['#refine-min-width', 'minWidth'],
            ['#refine-max-width', 'maxWidth'],
            ['#refine-min-length', 'minLength'],
            ['#refine-max-length', 'maxLength'],
            ['#refine-name', 'name'],
            ['#refine-surface', 'surface'],
            ['#refine-floodlit', 'floodlit'],
            ['#refine-goal-size', 'goalSize'],
            ['#refine-indoor', 'indoor'],
            ['#refine-nets', 'nets'],
            ['#refine-parking', 'parking'],
            ['#refine-changing-rooms', 'changingRooms'],
            ['#refine-showers', 'showers']
        ];

        for (var a in array) {
            this.change(array[a][0], array[a][1]);
        }
    },

    change: function (id, key) { //console.log('change:function (' + id + ', ' + key + ')');
        var _this = this;
        $(id).on('change keyup', function () { //console.log("$("+id+").on('change')");
            _this.opt[key] = $(this).val();
            PW.pitchSearch.refine();
            PW.pitchSearch.render();
        });
        $(id).trigger('change');
    },

    refine: function () {
        this.results = this.data.slice(0);

        for (var a in this.results) {
            var flag = true;
            var result = this.results[a];

            flag = this.test(flag, 'populated', {'slots': result.slots});
            flag = this.test(flag, 'date', {'slots': result.slots, 'date': this.opt.date, 'time': this.opt.time});
            flag = this.test(flag, 'match', {'result': result.pitch_size, 'refine': this.opt.size});
            flag = this.test(flag, 'match', {'result': result.pitch_surface, 'refine': this.opt.surface});
            flag = this.test(flag, 'match', {'result': result.pitch_floodlit, 'refine': this.opt.floodlit});
            flag = this.test(flag, 'match', {'result': result.pitch_goal_size, 'refine': this.opt.goalSize});
            flag = this.test(flag, 'match', {'result': result.pitch_indoor, 'refine': this.opt.indoor});
            flag = this.test(flag, 'match', {'result': result.pitch_nets, 'refine': this.opt.nets});
            flag = this.test(flag, 'match', {'result': result.pitch_parking, 'refine': this.opt.parking});
            flag = this.test(flag, 'match', {'result': result.venue_changing_rooms, 'refine': this.opt.changingRooms});
            flag = this.test(flag, 'match', {'result': result.venue_showers, 'refine': this.opt.showers});
            //flag = this.test(flag, 'above', {'result':this.results[a].pitch_surface, 'refine':this.opt.maxPrice});
            flag = this.test(flag, 'above', {'result': result.pitch_width, 'refine': this.opt.minWidth});
            flag = this.test(flag, 'below', {'result': result.pitch_width, 'refine': this.opt.maxWidth});
            flag = this.test(flag, 'above', {'result': result.pitch_length, 'refine': this.opt.minLength});
            flag = this.test(flag, 'below', {'result': result.pitch_length, 'refine': this.opt.maxLength});
            flag = this.test(flag, 'contains', {
                'text': result.pitch_pid.toLowerCase()
                    + result.venue_address.toLowerCase()
                    + result.venue_name.toLowerCase()
                    + result.venue_notes.toLowerCase()
                    + result.venue_nearest_station.toLowerCase(),
                'refine': this.opt.name.toLowerCase()
            });

            if (!flag) {
                this.results[a] = undefined;
            }
        }
        this.results = _.compact(this.results);
    },

    test: function (flag, type, options) {
        //console.log('test:function (' + flag + ', ' + type + ', ',options,')');
        switch (type) {
            case 'populated':
                if (options.slots.length == 0 ) {
                    flag = false;
                }
                break;
            case 'match':
                if (options.result != options.refine && options.refine && options.refine != "") {
                    flag = false;
                }
                break;
            case 'above':
                if (options.result < options.refine && options.refine) {
                    flag = false;
                }
                break;
            case 'below':
                if (options.result > options.refine && options.refine) {
                    flag = false;
                }
                break;
            case 'contains':
                if (options.text.indexOf(options.refine) == -1) {
                    flag = false;
                }
                break;
            case 'date':
                //console.log('test:function (' + flag + ', ' + type + ', ', options, ')');
                if (options.date) {
                    flag = false;
                    for (var b in options.slots) {
                        options.slots[b].valid = false;
                        if (options.date == options.slots[b].date) {
                            if (options.time) {
                                if (options.time >= options.slots[b].startTime && options.time <= options.slots[b].endTime) {
                                    flag = true;
                                    options.slots[b].valid = true;
                                    //break;
                                }
                            } else {
                                flag = true;
                                options.slots[b].valid = true;
                                //break;
                            }
                        }
                    }
                } else if (options.time) {
                    flag = false;
                    for (var b in options.slots) {
                        options.slots[b].valid = false;
                        if (options.time >= options.slots[b].startTime && options.time <= options.slots[b].endTime) {
                            flag = true;
                            options.slots[b].valid = true;
                            //break;
                        }
                    }
                } else {
                    for (var b in options.slots) {
                        options.slots[b].valid = true;
                    }
                }
                break;
        }
        return flag;
    },

    render: function () {
        $('#pitch-results').hide();
        $('#pitch-results').html('');
        var _this = this;
        var el;

        for (var a in _this.results) {
            el = {};
            el.card = $('<div />', {
                'class': 'card grey search-result clearfix',
                'style': 'display:block'
            });
            el.button = $('<a />', {
                'class': 'btn btn-small btn-primary pull-right',
                'style': 'margin-top:-5px;margin-bottom:-15px;clear:both',
                'href': _this.results[a].pitch_link,
                'html': '<span style="font-weight: 800">View »</span>'
            });
            el.h3 = $('<h3 />', {
                'style': 'margin-bottom: 5px;'
            });
            el.title = $('<a />', {
                'class': 'result-title',
                'style': 'margin-top:-5px;margin-bottom:-15px;clear:both',
                'href': _this.results[a].pitch_link,
                'html': _this.results[a].pitch_pid + ', ' + _this.results[a].venue_name
            });

            el.large = $('<div/>', {
                class: "large clearfix",
                style: "margin-bottom:10px"
            });

            el.imageLink = $('<a />', {
                'style': 'width:254px;display: block;float: left;margin-bottom: -15px;',
                'href': _this.results[a].pitch_link
            });

            el.image = $('<img />', {
                'style': 'margin-bottom:15px; border-radius:3px;',
                'src': _this.results[a].pitch_image_url
            });

            el.table = $('<table />', {
                'style': 'width: 355px;float: right;margin-bottom:0;',
                'class': 'table table-striped table-condensed table-bordered'
            });

            el.tr0 = $('<tr />', {
                'html': '<td><strong>Size</strong></td><td>' + _this.results[a].pitch_size + '</td>'
            });

            el.tr1 = $('<tr />', {
                'html': '<td><strong>Surface</strong></td><td>' + _this.results[a].pitch_surface + '</td>'
            });

            el.tr2 = $('<tr />', {
                'html': '<td><strong>Floodlit</strong></td><td>' + _this.results[a].pitch_floodlit + '</td>'
            });

            el.tr3 = $('<tr />', {
                'html': '<td><strong>Indoor</strong></td><td>' + _this.results[a].pitch_indoor + '</td>'
            });

            el.prices = $('<table/>', {
                'class': "table table-striped table-condensed table-bordered",
                'style': 'margin-bottom:0px'
            });

            el.pricestr = $('<tr />', {
                'html': '<th>Slot</th><th>Price</th><th style="width: 89px;"></th>',
                'style': 'display: table-row;'
            });

            var slotsArray = [];
            var tempEl;
            var count = 0;
            for (var b in _this.results[a].slots) {
                var obj = _this.results[a].slots[b];
                if (!obj.valid) {
                    continue;
                }
                count++;
                if (!obj.available) {
                    count--;
                }
                if (count == 4) {
                    break;
                }

                var form = '<td><strong>' + obj.day + '</strong> from <strong>' + obj.startTime + '</strong> until <strong>' + obj.endTime + '</strong></td>'
                    + '<td><del style="color:#777">£' + obj.price + '</del> <span style="font-weight:700">£' + (obj.price * 0.95).toFixed(2) + '</span></td>'
                    + '<td>'
                    + '<form action="/confirm-booking/" method="post" style="margin:0">'
                    + '<input type="hidden" name="form_pitch" value="' + obj.pitch + '">'
                    + '<input type="hidden" name="form_slot" value="' + obj.slot + '">'
                    + '<input type="hidden" name="form_date" value="' + obj.specialDate + '">'
                    + '<input type="hidden" name="form_price" value="' + obj.price * 0.95 + '">';
                if (obj.available) {
                    form += '<input type="submit" class="btn btn-mini btn-primary" style="font-weight:800;white-space:nowrap;" value="Book Now »">'
                        + '</form>';
                } else {
                    form += '<input type="submit" disabled="disabled" class="btn btn-mini btn-inverse" style="font-weight:800;white-space:nowrap;" value="Booked!">'
                        + '</form>';
                }

                tempEl = $('<tr />', {
                    'html': form
                });
                slotsArray.push(tempEl);
            }


            el.card.append(el.button);
            el.card.append(el.h3);
            el.h3.append(el.title);
            el.card.append(el.large);
            el.large.append(el.imageLink);
            el.imageLink.append(el.image);

            el.large.append(el.table);
            el.table.append(el.tr0);
            el.table.append(el.tr1);
            el.table.append(el.tr2);
            el.table.append(el.tr3);

            el.card.append(el.prices);
            el.prices.append('<thead></thead>');
            el.prices.find('thead').append(el.pricestr);
            el.prices.append('<tbody></tbody>');

            for (var b in slotsArray) {
                el.prices.find('tbody').append(slotsArray[b]);
            }


            /*
             <table id="booking-table" class="table table-striped table-condensed table-bordered" style="text-align: center;margin-bottom: 0;">
             <thead>
             <tr style="display: table-row;">
             <th>Slot</th>
             <th>Price</th>
             <th></th>
             </tr>
             </thead>
             <tbody>
             <tr data-date="22-04-2013" style="display: table-row;">
             <td>1800 - 1845</td>
             <td>£50</td>
             <td>
             <form action="/confirm-booking/" method="post" style="margin:0">
             <input type="hidden" name="form_pitch" value="353">
             <input type="hidden" name="form_slot" value="354">
             <input type="hidden" name="form_date" value="22-04-2013">
             <input type="hidden" name="form_price" value="50">

             <input type="submit" class="btn btn-mini btn-primary" style="font-weight:800;white-space:nowrap;" value="Book Now »">
             </form>
             </td>
             </tr>
             <tr data-date="22-04-2013" style="display: table-row;">
             <td>1845 - 1930</td>
             <td>£50</td>
             <td>
             <form action="/confirm-booking/" method="post" style="margin:0">
             <input type="hidden" name="form_pitch" value="353">
             <input type="hidden" name="form_slot" value="355">
             <input type="hidden" name="form_date" value="22-04-2013">
             <input type="hidden" name="form_price" value="50">

             </tbody>
             </table>
             */

            $('#pitch-results').append(el.card);
        }

        $('#pitch-results').fadeIn();
        //$('#result-count').html(_this.results.length + ' Pitches Available');
    },

    init: function (options) {
        this.options(options);
        this.load();
        this.events();
        this.render();
    }
};


